<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <link rel="stylesheet" href="styles/style.css">
        <link rel="stylesheet" href="styles/theme/atom-one-dark.css">
        <title>例子20-ES6/7常用语法介绍</title>
    </head>
    <body>
        <pre>
            <code>
                // 例子20

                function foo() {
                    setTimeout(() => {
                        console.log('id:', this.id);
                    }, 100);
                }
                var id = 21;
                foo.call({ id: 42 }); // "id: 42"

                //--------------------------------------------------------------------------

                function Timer() {
                    this.s1 = 0;
                    this.s2 = 0;
                    // 箭头函数
                    setInterval(() => this.s1++, 1000);
                    // 普通函数
                    setInterval(function () {
                        this.s2++;
                    }, 1000);
                }

                var timer = new Timer();

                setTimeout(() => console.log('s1: ', timer.s1), 3100);
                setTimeout(() => console.log('s2: ', timer.s2), 3100);
                // "s1: 3"
                // "s2: 0"

                //--------------------------------------------------------------------------

                // this指向的固定化，有利于封装回调函数
                var handler = {
                    id: '123456',

                    init: function() {
                        document.addEventListener('click', event => this.doSomething(event.type), false);
                    },

                    doSomething: function(type) {
                        console.log('Handling ' + type  + ' for ' + this.id);
                    }
                };

                //--------------------------------------------------------------------------

                // 箭头函数的实际转化
                // ES6
                function foo() {
                    setTimeout(() => {
                        console.log('id:', this.id);
                    }, 100);
                }

                // ES5
                function foo() {
                    var _this = this;

                    setTimeout(function () {
                        console.log('id:', _this.id);
                    }, 100);
                }
            </code>
        </pre>
        <script src="scripts/libs/highlight.pack.js"></script>
        <script src="scripts/20.js"></script>
        <script>
            hljs.initHighlightingOnLoad();
        </script>
    </body>
</html>